function newCrop(id, heroId, type, posRow, posCol) {
    return {
        id: id,
        pos: {
            row: posRow,
            col: posCol
        },
        curState : 0,
        type : type,
        heroId: heroId,
        timeRemaining: null
    }
}

//return null or index of the crop in hero's crops list
function isCropFound(hero, cl_crop) {
    var cropIndex = null;

    for(var index = 0; index < hero.crops.length; index++) {
        if(hero.crops[index].pos.row == cl_crop.pos.row
            &&
            hero.crops[index].pos.col == cl_crop.pos.col) {
            cropIndex = index;
        }
    }

    return cropIndex;
}

function createCrop(hero, cl_crop, callback) {
    hero.crops[hero.crops.length] = newCrop(hero.crops.length + 1, hero._id,
        cl_crop.type, cl_crop.pos.row, cl_crop.pos.col);

    var curCrop = hero.crops[hero.crops.length - 1];

    hero.markModified('crops');
    hero.save(function(err) {
        if(err) console.log(err.message);
        else {
            console.log('crop created for hero '+hero.name);
            callback(curCrop);
        }
    })
}

function updCrop(hero, crop, index, callback) {
    var curCrop = hero.crops[index];
        curCrop.curState = crop.curState;
        curCrop.timeRemaining = crop.timeRemaining;

    hero.markModified('crops');
    hero.save(function(err) {
        if(err) console.log(err.message);
        else {
            console.log('crop updated for hero : '+hero.name);
            callback(curCrop);
        }
    });
}

function updCropsTimers(hero, cropsList) {
    if(hero.crops.length != cropsList.length)
        console.log(' ERROR crops list different length : '+hero.crops.length +','+cropsList.length );

    for(var c in cropsList) {
        hero.crops[c].timeRemaining = cropsList[c].timeRemaining;
    }

    hero.markModified('crops');
    hero.save(function(err) {
        if(err) console.log('err updating hero crops : '+err.message);
    })
}

exports.createCrop = createCrop;
exports.updCrop = updCrop;
exports.updCropsTimers = updCropsTimers;
exports.isCropFound = isCropFound;